<template>
  <a-card :bordered="false">
    <!-- 操作按钮区域 -->
    <div class="table-operator" style="text-align: right">
      <a-button @click="handleAdd" type="primary" icon="plus" v-if="streaming">我要开播</a-button>
      <span v-if="!streaming">
      <a-button type="primary" @click="startStreaming" v-if="!beginStraming" >开始直播</a-button>
      <a-button type="danger" @click="stopStreaming" v-if="beginStraming">停止直播</a-button>
        </span>
    </div>
    <div class="container" v-if="!streaming">
      <div class="video-container">
        <video ref="video" autoplay playsinline></video>
      </div>
    </div>
    <!-- table区域-begin -->
    <div v-if="streaming">
      <template>
        <a-list item-layout="vertical" size="large"  :data-source="dataSource">
          <a-list-item slot="renderItem" slot-scope="item">
              <a-list-item-meta >
                <template #avatar>
                  <span>00:00:23</span>
                  <img width="120" alt="logo" :src="item.cover"/>
                </template>
                <template #title>
                  <a @click="handleDetail(item)">{{ item.title }}</a>
                </template>
                <div slot="description" style="font-size:12px;">
                  <span v-if="item.status==1">  未开始</span>
                  <span v-if="item.status==2" >  {{ item.beginTime }}-未结束</span>
                  <span v-if="item.status==3">  {{ item.beginTime }}-{{item.endTime}}</span>
                </div>
              </a-list-item-meta>
            </a-list-item>
        </a-list>
      </template>
    </div>

    <live-modal ref="modalForm" @ok="modalFormOka"></live-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import LiveModal from './modules/LiveModal'
  import {httpAction} from "@api/manage";
  import {  formatDateTime } from "@/utils/im/ChatUtils.js";
  export default {
    name: 'LiveList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      LiveModal
    },
    data () {
      return {
        description: '直播表管理页面',
        streaming: true,
        beginStraming:false,
        model: {},
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'直播标题',
            align:"center",
            dataIndex: 'title'
          },
          {
            title:'开始时间',
            align:"center",
            dataIndex: 'beginTime'
          },
          {
            title:'结束时间',
            align:"center",
            dataIndex: 'endTime'
          },
          {
            title:'直播时间',
            align:"center",
            dataIndex: 'duration'
          },
          {
            title:'联播群',
            align:"center",
            dataIndex: 'groupId'
          },
          {
            title:'直播状态',
            align:"center",
            dataIndex: 'status'
          },
          {
            title:'观看人数',
            align:"center",
            dataIndex: 'viewNum'
          },
          {
            title:'是共享屏幕',
            align:"center",
            dataIndex: 'isSharePage'
          },
          {
            title:'直播设置',
            align:"center",
            dataIndex: 'viewPermisson'
          },
          {
            title:'是否允许连线',
            align:"center",
            dataIndex: 'isAllowConnect'
          },
          {
            title:'开启直播回放',
            align:"center",
            dataIndex: 'isOpenRecord'
          },
          {
            title:'预览图片',
            align:"center",
            dataIndex: 'cover'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/satff/live/list",
          delete: "/satff/live/delete",
          deleteBatch: "/satff/live/deleteBatch",
          exportXlsUrl: "/satff/live/exportXls",
          importExcelUrl: "satff/live/importExcel",
          edit: "/satff/live/edit",

        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
    this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      initDictConfig(){
      },
      modalFormOka() {
        // 新增/修改 成功时，重载列表
        this.loadData();
        //清空列表选中
        this.onClearSelected()
        this.model = this.dataSource[0];
        this.streaming = false;
        alert()
      },
      async startStreaming() {
        try {
          this.model.beginTime = formatDateTime(new Date());
          this.model.status = 2;
          httpAction(this.url.edit,this.model,"put").then(async (res) => {
            if (res.success) {
              // 请求访问摄像头
              this.mediaStream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
              const videoElement = this.$refs.video;
              this.beginStraming = true;
              videoElement.srcObject = this.mediaStream;
            } else {
              that.$message.warning(res.message);
            }
          })
        } catch (error) {
          console.error("无法访问摄像头: ", error);
          this.$message.error("无法访问摄像头，请检查权限设置。");
        }
      },
      stopStreaming() {
        this.model.endTime = formatDateTime(new Date());
        this.model.status = 3;
        httpAction(this.url.edit,this.model,"put").then(async (res) => {
          if (res.success) {
                if (this.mediaStream) {
                  // 停止所有视频轨道
                  this.streaming = true;
                  this.beginStraming = false;
                  this.mediaStream.getTracks().forEach(track => track.stop());
                  this.mediaStream = null;
                  const videoElement = this.$refs.video;
                  videoElement.srcObject = null; // 清空视频源
                }
          } else {
            that.$message.warning(res.message);
          }
        })
        // 新增/修改 成功时，重载列表
        this.loadData();
        //清空列表选中
        this.onClearSelected()
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'title',text:'直播标题',dictCode:''})
        fieldList.push({type:'datetime',value:'beginTime',text:'开始时间'})
        fieldList.push({type:'datetime',value:'endTime',text:'结束时间'})
        fieldList.push({type:'datetime',value:'duration',text:'直播时间'})
        fieldList.push({type:'string',value:'groupId',text:'联播群',dictCode:''})
        fieldList.push({type:'string',value:'status',text:'直播状态',dictCode:''})
        fieldList.push({type:'int',value:'viewNum',text:'观看人数',dictCode:''})
        fieldList.push({type:'string',value:'isSharePage',text:'是共享屏幕',dictCode:''})
        fieldList.push({type:'string',value:'viewPermisson',text:'直播设置',dictCode:''})
        fieldList.push({type:'int',value:'isAllowConnect',text:'是否允许连线',dictCode:''})
        fieldList.push({type:'string',value:'isOpenRecord',text:'开启直播回放',dictCode:''})
        fieldList.push({type:'string',value:'cover',text:'预览图片',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
<style scoped>
.container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.video-container {
  width: 100%;
  height: 400px;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

video {
  width: 100%;
  height: 100%;
}
</style>